<template>
  <div class="view-article">
    <div class="header-bg">
      <!-- 职位信息 -->
      <div class="article-info">
        <!--职位标题 -->
        <div class="title">{{ article.title }}</div>
        <!-- 薪资范围 -->
        <div class="money">{{ article.money }}</div>
        <!-- 职位信息提示 -->
        <div class="article-info-tip" ref="tip">
          <span class="time">
            <i class="el-icon-time"></i> 发布于{{
              String(article.created_time).substring(0, 10)
            }}
            |
          </span>
          <span v-show="article.is_recommend"
            ><i class="el-icon-star-on"></i> 推荐 |
          </span>
          <span class="category"
            ><i class="el-icon-menu"></i> {{ article.category_name }} |
          </span>
          <span class="comment"
            ><i class="el-icon-s-comment"></i> {{ currentMessagesTotal }} |
          </span>
        </div>
        <el-button type="primary" round class="apply-btn" @click="apply"
          >立即申请</el-button
        >
      </div>
    </div>
    <div class="main" style="width: calc(100vw - 100px)">
      <div class="item left-height ql-snow">
        <div class="desprition-text">工作描述</div>
        <div
          ref="aContent"
          id="aContent"
          class="article-conntent ql-editor"
          v-html="article.content"
        ></div>
        <!-- 评论 -->
        <div class="comment">
          <!-- 评论区域 -->
          <div class="comment-content">
            <ul>
              <li
                v-for="(item, index) in currentMessagesAndUserInfo"
                :key="index"
              >
                <img :src="item.avatar" alt="" />
                <div class="info">
                  <span class="user-item">
                    {{ item.nickname + " ： " }}
                  </span>
                  <span>{{ item.created_time }}</span>
                  <p class="comment-item">
                    {{ item.content }}
                  </p>
                </div>
              </li>
            </ul>
          </div>
          <div class="comment-input">
            <textarea
              v-model.trim="newContent"
              @input="handleInput"
              :maxlength="handleStopWrite()"
              placeholder="请发表您的评论"
            ></textarea>
            <button class="comment-btn" @click="handleSubmit">发表</button>
            <el-button
              type="warning"
              icon="el-icon-star-off"
              circle
              @click="collectArticle()"
            ></el-button>
          </div>
          <div class="input-tip">
            {{ "字数：" + inputLength + "/" + maxInputLength }}
          </div>
        </div>
      </div>
    </div>

    <!-- 申请弹窗 -->
    <ApplyModal ref="applyModalRef" />
  </div>
</template>

<script>
import LayoutCol from "@/components/LayoutCol.vue";
import followBtn from "@/components/followBtn.vue";
import ApplyModal from "../../components/applyModal.vue";
export default {
  name: "HomeViewArticle",
  components: { LayoutCol, followBtn, ApplyModal },
  data() {
    return {
      article: {},
      currentCategory: "",
      currentMessagesAndUserInfo: [],
      currentMessagesTotal: 0,
      currentUserId: "",
      newContent: "",
      inputLength: 0,
      maxInputLength: 100,
      dirTree: [],
      userId: 0,
      // 作者信息
      editorInfo: {},
    };
  },
  methods: {
    // 获取登录用户信息
    getUserInfo() {
      // GET /login/getinfo
      this.$http.get(`/login/getinfo`).then((res) => {
        const { code, msg, result } = res;
        if (code == 0) {
          this.userId = result.id;
        }
      });
    },
    getArticle() {
      // 当前职位的id this.$route.query.id
      this.$http.get(`/articles?id=${this.$route.query.id}`).then((res) => {
        this.article = res.result[0];
        this.editorInfo.userId = res.result[0].user_id;
        this.getCurrentMessagesAndUserInfo(this.article);
        this.getEditorInfo();

        this.$http
          .put(`/articles/view_num?id=${this.$route.query.id}`)
          .then((res) => {
            if (res.code == 0) {
              // console.log("职位访问量+1");
            }
          });
      });
    },
    getCurrentMessagesAndUserInfo(article) {
      this.$http
        .get(`/comments/userinfo/?article_id=${article.id}`)
        .then((res) => {
          this.currentMessagesTotal = res.result.total;
          this.currentMessagesAndUserInfo = res.result.msg_userinfo.reverse();
        });
    },
    handleSubmit() {
      this.$http.get("/login/getinfo").then((res) => {
        // console.log('loginInfo', res)
        if (res.code == 0) {
          this.currentUserId = res.result.id;
        } else {
          this.$message({
            type: "error",
            message: "未登录，请先登录再评论!",
          });
          return;
        }
        let newContent = {
          content: this.newContent,
          user_id: this.currentUserId,
          article_id: this.article.id,
          approved: 1,
        };
        // console.log(newContent)
        if (newContent.content == "") {
          this.$message({
            type: "error",
            message: "输入为空，请重新输入!",
          });
          return;
        }
        this.$http.post(`/comments/`, newContent).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: "评论成功!",
            });
            this.newContent = "";
            this.inputLength = 0;
            this.getCurrentMessagesAndUserInfo(this.article);
          } else {
            this.$message({
              type: "error",
              message: "评论失败!",
            });
          }
        });
      });
    },
    getCurrentLoginUser() {
      // GET /login/getinfo
      this.$http.get("/login/getinfo").then((res) => {
        // console.log('loginInfo', res)
        // 优化点,需要判断登录
        if (res.code == 0) {
          this.currentUserId = res.result.id;
        }
      });
    },
    handleInput() {
      this.inputLength = this.newContent.length;
    },
    handleStopWrite() {
      if (this.inputLength >= this.maxInputLength) {
        return 0;
      } else {
        return 100;
      }
    },
    toTree(data) {
      // 删除 所有 children,以防止多次调用
      data.forEach(function (item) {
        delete item.children;
      });

      // 将数据存储为 以 id 为 KEY 的 map 索引数据列
      var map = {};
      data.forEach(function (item) {
        map[item.id] = item;
      });
      var val = [];
      data.forEach(function (item) {
        // 以当前遍历项的pid,去map对象中找到索引的id
        var parent = map[item.p_id];
        // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
          val.push(item);
        }
      });
      return val;
    },
    makeDirTree() {
      if (true) {
        this.$nextTick(() => {
          // 定义参与目录生成的标签
          const tocTags = ["H1", "H2", "H3", "H4", "H5", "H6"];
          // 目录树结果
          const tocArr = [];
          // 获取所有标题标签
          const headDoms = Array.from(this.$refs.aContent.childNodes).filter(
            (item) => tocTags.includes(item.tagName)
          );
          // 遍历标题标签
          headDoms.forEach((item, index, arr) => {
            // 给标题添加id
            item.id = `h-${index + 1}`;
            // 获取当前节点前面的节点
            let prevs = arr.filter((i, j) => j < index);
            // 过滤前面的节点为合理节点
            // 如 h3节点前  只能为 h1 h2 h3
            prevs = prevs.filter((i) =>
              tocTags
                .filter(
                  (i, j) => j <= tocTags.findIndex((i) => i == item.tagName)
                )
                .includes(i.tagName)
            );
            // 对前面的节点进行排序，距离自身节点近的排在前面
            // 如 div > p > span > img  当前为img
            // 常规获取节点为 [div,p,span,img]
            // 排序后获取节点为 [img,span,p,div]
            prevs = prevs.sort(
              (a, b) => -a.id.replace("h-", "") - b.id.replace("h-", "")
            );
            // 查询距离自身节点最近的不同于当前标签的节点
            const prev = prevs.find((i) => i.tagName != item.tagName);

            tocArr.push({
              id: index + 1, // 抛出id
              link: "h-" + (index + 1), // 抛出id
              tag: item.tagName, // 抛出标签名称
              label: item.innerText, // 抛出标题
              p_id:
                item.tagName == "H1" ? 0 : Number(prev.id.replace("h-", "")), // 抛出父级id
            });
          });

          // 使用上述方法生成树 最后在el-tree的data中使用 tocData即可
          this.dirTree = this.toTree(tocArr);
          // console.log(this.dirTree)
        });
      }
    },
    // 收藏
    collectArticle() {
      this.$http
        .post("/collect", {
          user_id: this.userId,
          article_id: this.article.id,
          article_name: this.article.title,
        })
        .then((res) => {
          if (res.code == 0) {
            this.$message({
              showClose: true,
              message: "收藏成功！！",
              type: "success",
            });
          }
        });
    },
    // 获取作者信息
    // 获取登录用户信息
    getEditorInfo() {
      // GET /login/getinfo
      this.$http.get(`users/?id=${this.editorInfo.userId}`).then((res) => {
        this.editorInfo = res.result[0];
      });
    },
    addVisCount() {},

    apply() {
      this.$http.get("/login/getinfo").then((res) => {
        if (res.code == 0) {
          this.$refs.applyModalRef.onShow(this.article);
        } else {
          this.$message({
            type: "error",
            message: "未登录，请先登录再进行申请",
          });
          return;
        }
      });
    },
  },
  mounted() {
    document.documentElement.scrollIntoView({
      block: "start",
      behavior: "smooth", // 平滑滚动
    });
    // 当前职位的id this.$route.query.id

    this.getArticle();
    this.getCurrentLoginUser();
    this.getUserInfo();
  },
  updated() {
    this.makeDirTree();
  },
};
</script>

<style lang="less" scoped>
@import "~styles/theme.styl";

.header-bg {
  width: 100%;
  height: 400px;
  margin-top: 80px;
  margin-bottom: 20px;
  background-color: white;
  background-image: url("../../assets/images/wave-bg.png");
  background-size: contain !important;
  padding-top: 50px;

  .article-info {
    margin-left: 300px;
    width: 1100px;
    height: 300px;
    padding-top: 60px;
    line-height: 200px;
    background-color: rgba(255, 255, 255, 0.3);
    border-radius: 15px;
    padding-left: 20px;
    line-height: 30px;
    position: relative;

    .title {
      font-size: 30px;
      margin-bottom: 30px;
    }

    .money {
      position: absolute;
      right: 54px;
      top: 49px;
      font-size: 43px;
      font-weight: bold;
      color: #f26d49;
    }

    .apply-btn {
      position: absolute;
      bottom: 50px;
      right: 30px;
    }
  }
}

.left-height {
  .article-conntent {
    font-size: 18px;
    line-height: 35px;

    padding: 20px 30px 20px 30px;
  }
}

.view-article {
  transition: all 0.5s;

  .head {
    // position: relative
    height: 100vh;

    .cover-picture {
      width: 100%;
      height: 100vh;
    }

    .article-info {
      // 职位标题
      h1 {
        font-size: 50px;
        font-family: "STXinwei", "KaiTi", "隶书";
        color: var(--color);
        transition: all 0.5s;
      }

      // 职位信息提示
      .article-info-tip {
        width: 40%;
        height: 60px;
        margin: 30px 0 60px 0;
        padding: 0 15px;
        line-height: 60px;
        text-align: center;
        font-size: 20px;
        border-radius: 30px;
        background: var(--transparentDiv);

        p {
          font-weight: bolder;
        }
      }
    }
  }

  .main {
    .comment {
      width: 100%;
      display: flex;
      flex-direction: column;
      justify-content: center;
      position: relative;

      .comment-input {
        width: 100%;
        display: flex;
        justify-content: center;
        align-items: flex-end;
        margin: 0px;
        border-top: 0.1px solid #9aa0a6;
        padding-top: 30px;
        padding-bottom: 30px;
        margin-bottom: 20px;

        textarea {
          background-color: var(--mask);
          box-sizing: border-box;
          width: 80%;
          height: 100px;
          padding: 10px;
          outline: none;
          border: 0.1px solid #9aa0a6;
          border-radius: 10px;
          margin-right: 10px;
          color: var(--color);
          font-size: 16px;
          resize: none;
        }

        .comment-btn {
          width: 120px;
          height: 40px;
          border: none;
          border-radius: 20px;
          color: #fff;
          font-size: 20px;
          background-color: #0fb37d;
          cursor: pointer;
          margin-right: 15px;
        }
      }

      .input-tip {
        position: relative;
        top: 15%;
        left: 75%;
      }

      .comment-content {
        li {
          margin: 20px 20px;
          display: flex;
        }

        img {
          width: 40px;
          height: 40px;
          margin-top: 15px;
          border-radius: 30px;
          border: 0.1px solid #9aa0a6;
        }

        .info {
          padding-left: 15px;
        }

        .user-item {
          color: var(--color);
          font-weight: bold;
          line-height: 60px;
        }

        .comment-item {
          position: relative;
          top: -10px;
          width: 100%;
          // height: 60px
          color: var(--color);
          word-break: break-all; /* 强制英文单词断行，中文也适用 */
          word-wrap: break-word; /* 自动换行 */
        }
      }
    }

    .dictionary {
      width: 100%;
      padding: 10px;

      .dictionary-name {
        display: block;
        text-align: center;
        font-size: 40px;
        font-family: "STXinwei";
        text-decoration: none;
        margin-bottom: 20px;
        color: var(--color);
      }

      .first-title,
      .second-title,
      .third-title {
        font-family: "KaiTi";
        transition: all 0.5s;
      }

      .first-title:hover,
      .second-title:hover,
      .third-title:hover {
        color: #ff638a;
      }

      .first-title {
        max-size: 100%;
        overflow: hidden;
        font-size: 25px;
        text-decoration: none;
        line-height: 40px;
        font-weight: bold;
        color: #000;
        color: var(--color);
      }

      .second-title {
        max-size: 100%;
        overflow: hidden;
        font-size: 20px;
        text-decoration: none;
        margin-left: 25px;
        line-height: 30px;
        color: #000;
        color: var(--color);
      }

      .third-title {
        max-size: 100%;
        overflow: hidden;
        font-size: 15px;
        text-decoration: none;
        margin-left: 50px;
        line-height: 20px;
        color: #000;
        color: var(--color);
      }
    }

    .editorInfo {
      height: 220px;

      .touxiang {
        display: flex;

        .editorText {
          margin-top: 10px;
          margin-left: 15px;
        }
      }
    }
  }
}

.followBtn {
  margin: auto;
}

.ql-snow {
  width: 1100px;
  margin-left: 270px;
  border-radius: 15px;
  padding: 20px;
  box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
  margin-bottom: 30px;
}

.desprition-text {
  font-size: 18px;
  font-weight: bold;
}
</style>
